package com.decent.ejfadmin.product.service.impl;


import com.decent.ejfadmin.common.bean.SupUser;
import com.decent.ejfadmin.common.bean.SupplyProduct;
import com.decent.ejfadmin.common.bean.SupplyProductPrice;
import com.decent.ejfadmin.product.service.PriceService;
import com.decent.ejfadmin.product.service.SupplyProductService;
import com.decent.ejfadmin.user.service.UserService;
import com.decent.ejfadmin.common.bean.SupplyCard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 价格检测
 *
 * @author hejunlei
 */
@Service
public class PriceServiceImpl implements PriceService {
    @Autowired
    private UserService userService;
    @Autowired
    private SupplyProductService supplyProductService;

    /**
     * 销卡回调判断符合的价格
     * 处理成功时若销卡金额与会员上传的面值不同则重新获取 会员折扣userPrice
     * 若处理为其他状态或者销卡金额与会员的上传面值相同则不处理
     *
     * @param status      状态
     * @param card        销卡数据
     * @param actualPrice 销卡面值
     * @return 价格
     */
    @Override
    public BigDecimal getUserPriceInCallBack(Integer status, SupplyCard card, BigDecimal actualPrice) {
        if (!status.equals(1) || actualPrice.compareTo(card.getFace()) == 0) {
            return card.getUserPrice();
        }
        String area = card.getSupplyArea().equals(0) ? "全国" : card.getArea();
        SupUser users = userService.queryUsersById(card.getUserId());

        SupplyProduct product = supplyProductService.queryProduct(area, card.getFace().intValue(), card.getProductType());
        //获取折扣乘以十了
        SupplyProductPrice supplyProductPrice = supplyProductService.queryUserProductPrice(users, product.getId(), card.getSpeed());

        if (Objects.isNull(supplyProductPrice)
                || supplyProductPrice.getMaxPrice().compareTo(BigDecimal.ZERO) <= 0
                || supplyProductPrice.getMinPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return card.getUserPrice();
        }
        return card.getUserPrice().min(supplyProductPrice.getMaxPrice().divide(BigDecimal.TEN));
    }

}